package com.sliansoft.wechat.contacts;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.sliansoft.wechat.common.HTTPUtil;
import com.sliansoft.wechat.platform.contact.model.Department;
import com.sliansoft.wechat.platform.contact.model.Employee;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class EmployeeUtil {

	public static final String CREATE_EMPLOYEE = "https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=ACCESS_TOKEN";
	
	public static final String UPDATE_EMPLOYEE = "https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token=ACCESS_TOKEN";
	
	public static final String DELETE_EMPLOYEE = "https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token=ACCESS_TOKEN&userid=USERID";
	
	public static final String DELETE_EMPLOYEES = "https://qyapi.weixin.qq.com/cgi-bin/user/batchdelete?access_token=ACCESS_TOKEN";
	
	public static final String GET_EMPLOYEE = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&userid=USERID";
	
	public static final String GET_EMPLOYEES_FROM_DEPARTMENT = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token=ACCESS_TOKEN&department_id=DEPARTMENT_ID&fetch_child=FETCH_CHILD&status=STATUS";
	
	public static final String GET_EMPLOYEE_DETIALS = "https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=ACCESS_TOKEN&department_id=DEPARTMENT_ID&fetch_child=FETCH_CHILD&status=STATUS";
	
	public static final String INVITE_EMPLOYEE = "https://qyapi.weixin.qq.com/cgi-bin/invite/send?access_token=ACCESS_TOKEN";
	
	public static String getDepartmentIds(List<Department> departments){
		StringBuilder sb = new StringBuilder();
		sb.append("[");
		departments.forEach((department) -> {
			sb.append(department.getDepartmentid() + ",");
		});
		if(departments.size() > 0) sb.deleteCharAt(sb.length()-1);
		sb.append("]");
		return sb.toString();
	}
	
	public static boolean createEmployee(String accessToken, Employee employee, List<Department> departments){
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("userid", employee.getUserid());
		jsonObject.put("name", employee.getName());
		jsonObject.put("department", getDepartmentIds(departments));
		jsonObject.put("position", employee.getPosition());
		jsonObject.put("mobile", employee.getMobile());
		jsonObject.put("gender", employee.getGender());
		jsonObject.put("email", employee.getEmail());
		jsonObject.put("weixinid", employee.getWeixinId());
		jsonObject.put("avatar_mediaid", employee.getAvatar());
		jsonObject.put("extattr", employee.getExrattr());
		String result = HTTPUtil.postReq(CREATE_EMPLOYEE.replace("ACCESS_TOKEN", accessToken), jsonObject.toString(), "application/json;charset=utf-8");
		JSONObject responseJSON = JSONObject.fromObject(result);
		if(0 == (Integer)responseJSON.get("errcode") && "created".equals(responseJSON.get("errmsg"))){
			return true;
		}
		return false;
	}
	
	public static boolean updateEmployee(String accessToken, Employee employee, List<Department> departments){
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("userid", employee.getUserid());
		jsonObject.put("name", employee.getName());
		jsonObject.put("department", getDepartmentIds(departments));
		jsonObject.put("position", employee.getPosition());
		jsonObject.put("mobile", employee.getMobile());
		jsonObject.put("gender", employee.getGender());
		jsonObject.put("email", employee.getEmail());
		jsonObject.put("weixinid", employee.getWeixinId());
		jsonObject.put("enable", employee.getStatus());
		jsonObject.put("avatar_mediaid", employee.getAvatar());
		jsonObject.put("extattr", employee.getExrattr());
		String result = HTTPUtil.postReq(UPDATE_EMPLOYEE.replace("ACCESS_TOKEN", accessToken), jsonObject.toString(), "application/json;charset=utf-8");
		JSONObject responseJSON = JSONObject.fromObject(result);
		if(0 == (Integer)responseJSON.get("errcode") && "updated".equals(responseJSON.get("errmsg"))){
			return true;
		}
		return false;
	}
	
	public static boolean deleteEmployee(String accessToken, String userId){
		String result = HTTPUtil.sendGet(DELETE_EMPLOYEE.replace("ACCESS_TOKEN", accessToken).replace("USERID", userId));
		JSONObject responseJSON = JSONObject.fromObject(result);
		if(0 == (Integer)responseJSON.get("errcode") && "deleted".equals(responseJSON.get("errmsg"))){
			return true;
		}
		return false;
	}
	
	public static boolean deleteEmployees(String accessToken, List<Employee> employees){
		JSONObject jsonObject = new JSONObject();
		JSONArray jsonArray = new JSONArray();
		for(Employee employee : employees){
			jsonArray.add(employee.getUserid());
		}
		jsonObject.put("useridlist", jsonArray);
		String result = HTTPUtil.postReq(DELETE_EMPLOYEES.replace("ACCESS_TOKEN", accessToken), jsonObject.toString(), "application/json;charset=utf-8");
		JSONObject responseJSON = JSONObject.fromObject(result);
		if(0 == (Integer)responseJSON.get("errcode") && "deleted".equals(responseJSON.get("errmsg"))){
			return true;
		}
		return false;
	}
	
	public static Employee getEmployee(String accessToken, String userId, List<String> departmentIds){
		String result = HTTPUtil.sendGet(GET_EMPLOYEE.replace("ACCESS_TOKEN", accessToken).replace("USERID", userId));
		JSONObject responseJSON = JSONObject.fromObject(result);
		if(0 == (Integer)responseJSON.get("errcode") && "ok".equals(responseJSON.get("errmsg"))){
			Employee employee = new Employee();
			employee.setUserid(responseJSON.getString("userid"));
			employee.setName(responseJSON.getString("name"));
			JSONArray array = responseJSON.getJSONArray("department");
			for(int i = 0; i < array.size(); i++){
				departmentIds.add(array.getString(i));
			}
			employee.setPosition(responseJSON.getString("position"));
			employee.setMobile(responseJSON.getString("mobile"));
			employee.setGender(responseJSON.getInt("gender"));
			employee.setEmail(responseJSON.getString("email"));
			employee.setWeixinId(responseJSON.getString("weixinid"));
			employee.setAvatar(responseJSON.getString("avatar"));
			employee.setStatus(responseJSON.getString("status"));
			employee.setExrattr(responseJSON.getString("extattr"));
			return employee;
		}
		return null;
	}
	
	public static List<Employee> getEmployeesByDepartment(String accessToken, String departmentId, Integer fetchChild, Integer status, Map<String,List<String>> map){
		String result = HTTPUtil.sendGet(GET_EMPLOYEES_FROM_DEPARTMENT.replace("ACCESS_TOKEN", accessToken).replace("DEPARTMENT_ID", departmentId).replace("FETCH_CHILD", fetchChild.toString()).replace("STATUS", status.toString()));
		JSONObject responseJSON = JSONObject.fromObject(result);
		System.out.println(responseJSON);
		if(0 == (Integer)responseJSON.get("errcode") && "ok".equals(responseJSON.get("errmsg"))){
			JSONArray employees = responseJSON.getJSONArray("userlist");
			if(employees==null)
				System.out.println("===========");
			else 
				System.out.println(employees);
			System.out.println("-------------------------------");
			List<Employee> list = new ArrayList<Employee>();
			for(int i = 0; i < employees.size(); i++){
				JSONObject obj = employees.getJSONObject(i);
				Employee employee = new Employee();
				employee.setUserid(obj.getString("userid"));
				employee.setName(obj.getString("name"));
				JSONArray array = obj.getJSONArray("department");
				List<String> departmentIds = new ArrayList<String>();
				for(int j = 0; j < array.size(); j++){
					departmentIds.add(array.getString(j));
				}
				map.put(employee.getUserid(), departmentIds);
				list.add(employee);
			}
			return list;
		}
		return null;
	}
	
	public static List<Employee> getEmployeesByDepDetials(String accessToken,Integer departmentId,Integer fetchChild,Integer status,Map<String,List<String>> map){
		String result=HTTPUtil.sendGet(GET_EMPLOYEE_DETIALS.replace("ACCESS_TOKEN", accessToken)
				.replace("DEPARTMENT_ID", departmentId.toString()).replace("FETCH_CHILD", fetchChild.toString()).replace("STATUS", status.toString()));
		JSONObject responseJSON = JSONObject.fromObject(result);
		System.out.println(responseJSON+"==============="+departmentId);
		if(0 == (Integer)responseJSON.get("errcode")&&"ok".equals(responseJSON.get("errmsg"))){
			JSONArray employees = responseJSON.getJSONArray("userlist");
			List<Employee> list = new ArrayList<Employee>();
			for(int i = 0; i < employees.size(); i++){
				JSONObject obj = employees.getJSONObject(i);
				Employee employee = new Employee();
				employee.setUserid(obj.getString("userid"));
				employee.setName(obj.getString("name"));
				try {
					employee.setPosition(obj.getString("position"));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					employee.setPosition(null);
				}
				try {
					employee.setMobile(obj.getString("mobile"));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					employee.setMobile(null);
				}
				employee.setGender(Integer.parseInt(obj.getString("gender")));
				try {
					employee.setEmail(obj.getString("email"));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					employee.setEmail(null);
				}
				employee.setStatus(obj.getString("status"));
				if ("1".equals(obj.getString("status"))) {
					employee.setWeixinId(validate(obj.getString("weixinid")));
				}
				try {
					employee.setAvatar(obj.getString("avatar"));
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					
				}
				try {
					employee.setExrattr(obj.getString("extattr"));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					employee.setExrattr(null);
				}
				JSONArray array = obj.getJSONArray("department");
				List<String> departmentIds = new ArrayList<String>();
				for(int j = 0; j < array.size(); j++){
					departmentIds.add(array.getString(j));
				}
//				System.out.println(employee.toString());
				map.put(employee.getUserid(), departmentIds);
				list.add(employee);
			}
			return list;

		}
		return null;
	}
	
	private static String validate(String str){
		if(str==null)
			return null;
		return str;
			
	}
	
	public static boolean inviteEmp(String accessToken,String userId){
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("userid", userId);
		String result=HTTPUtil.postReq(INVITE_EMPLOYEE.replace("ACCESS_TOKEN", accessToken), jsonObject.toString(), "application/json;charset=utf-8");
		JSONObject responseJSON=JSONObject.fromObject(result);
		if(0 == (Integer)responseJSON.get("errcode")&&"ok".equals(responseJSON.get("errmsg"))){
			return true;
		}
		return false;
	}
}
